<template>
	<view class="container">
		<view class="main" v-if="shopAddressData.length">
			<view class="nav">
				<view class="header">
					<view class="left" v-if="orderType == 'takein'">
						<view class="store-name">
							<text>{{ shopDetailData.shopName }}</text>
							<view class="iconfont iconarrow-right"></view>
						</view>
						<view class="store-location">
							<image src='/static/images/order/location.png' style="width: 30rpx; height: 30rpx;"
								class="mr-10"></image>
							<text>距离您 1{{ shopDetailData.distance}} <text>米</text></text>
						</view>
					</view>
					<view class="left" v-else>
						<view class="d-flex">
							<image src='/static/images/order/location.png' style="width: 30rpx; height: 30rpx;"
								class="mr-10"></image>
							<view class="font-size-extra-lg text-color-base font-weight-bold text-truncate">
								{{ userOrderAddress.addressDetail }}
							</view>
						</view>
						<view class="font-size-sm text-color-assist overflow-hidden text-truncate">
							由<text class="text-color-base" style="margin: 0 10rpx">{{ '胖东来超市配送'}}</text>配送
						</view>
					</view>
					<view class="right">
						<view class="dinein" :class="{active: orderType == 'takein'}" @tap="takein('takein')">
							<text>自取</text>
						</view>
						<view class="takeout" :class="{active: orderType == 'takeout'}" @tap="takout('takeout')">
							<text>外卖</text>
						</view>
					</view>
				</view>
				<view class="coupon">
					<text class="title">"霸气mini卡"超级购券活动，赶紧去购买</text>
					<view class="iconfont iconarrow-right"></view>
				</view>
			</view>
			<view class="content">
				<scroll-view class="menus" :scroll-into-view="menuScrollIntoView" scroll-with-animation scroll-y>
					<view class="wrapper">
						<view class="menu" :id="`menu-${item.id}`" :class="{'current': item.id === currentCateId}"
							v-for="(item, index) in shopAddressData" :key="index" @tap="handleMenuTap(item.id)">
							<text>{{ item.categoryName }}</text>
							<view class="dot" v-show="menuCartNum(item.id)">{{ menuCartNum(item.id) }}</view>
						</view>
					</view>
				</scroll-view>
				<scroll-view class="goods" :style="{ height: `${scrollProHei}px` }" scroll-with-animation scroll-y
					:scroll-top="cateScrollTop" @scroll="handleGoodsScroll">
					<view class="wrapper">
						<swiper class="ads" id="ads" autoplay :interval="3000" indicator-dots>
							<swiper-item v-for="(item, index) in ads" :key='index'>
								<image :src="item.image"></image>
							</swiper-item>
						</swiper>
						<view class="list">
							<!-- category begin -->
							<view class="category" v-for="(item, index) in shopAddressData" :key="index"
								:id="`cate-${item.id}`">
								<view class="title">
									<text>{{ item.categoryName }}</text>
									<!-- <image :src="item.icon" class="icon"></image> -->
								</view>
								<view class="items">
									<!-- 商品 begin -->
									<view class="good" v-for="(good, key) in item.goodsLists" :key="key">
										<image :src="getImgUrl+good.goodsImg" class="image"
											@tap="showGoodDetailModal(item, good)">
										</image>
										<view class="right">
											<text class="name">{{ good.goodsName }}</text>
											<text class="tips">{{ good.introduction }}</text>
											<view class="price_and_action">
												<text class="price">￥{{ good.price }}</text>
												<!-- 	<view class="btn-group" v-if="good.use_property">
													<button type="primary" class="btn property_btn" hover-class="none"
														size="mini" @tap="showGoodDetailModal(item, good)">
														选规格
													</button>
													<view class="dot" v-show="goodCartNum(good.id)">
														{{ goodCartNum(good.id) }}
													</view>
												</view> -->
												<view class="btn-group">
													<button type="default" v-show="goodCartNum(good.id)" plain
														class="btn reduce_btn" size="mini" hover-class="none"
														@tap="handleReduceFromCart(item, good)">
														<view class="iconfont icon-jianhao"></view>
													</button>
													<view class="number" v-show="goodCartNum(good.id)">
														{{ goodCartNum(good.id) }}
													</view>
													<button type="primary" class="btn add_btn" size="min"
														hover-class="none" @tap="handleAddToCart(item, good, 1)">
														<view class="iconfont icon-plus"></view>
													</button>
												</view>
											</view>
										</view>
									</view>
									<!-- 商品 end -->
								</view>
							</view>
							<!-- category end -->
						</view>
					</view>

					<view class="" style="height: 100px;">

					</view>
				</scroll-view>
				<!-- goods list end -->
			</view>
			<!-- content end -->
			<!-- 购物车栏 begin -->
			<view class="cart-box" v-if="cart.length > 0">
				<view class="mark">
					<image src="/static/images/menu/cart.png" class="cart-img" @tap="openCartPopup"></image>
					<view class="tag">{{ getCartGoodsNumber }}</view>
				</view>
				<view class="price">￥{{ getCartGoodsPrice }}</view>
				<button type="primary" class="pay-btn" @tap="toPay" :disabled="disabledPay">
					{{ disabledPay ? `差${spread}元起送` : '去结算' }}
				</button>
			</view>
			<!-- 购物车栏 end -->
		</view>
		<!-- 商品详情模态框 begin -->
		<modal :show="goodDetailModalVisible" class="good-detail-modal" color="#5A5B5C" width="90%" custom
			padding="0rpx" radius="12rpx">
			<view class="cover">
				<image v-if=" goodsDetail.goodsImg" :src="getImgUrl+ goodsDetail.goodsImg" class="image"></image>
				<view class="btn-group">
					<image src="/static/images/menu/share-good.png"></image>
					<image src="/static/images/menu/close.png" @tap="closeGoodDetailModal"></image>
				</view>
			</view>
			<scroll-view class="detail" scroll-y>
				<view class="wrapper">
					<view class="basic">
						<view class="name">{{ goodsDetail.goodsName }}</view>
						<view class="tips">{{ goodsDetail.introduction }}</view>
					</view>

				</view>
			</scroll-view>
			<view class="action">
				<view class="left">
					<view class="price">￥{{ goodsDetail.price }}</view>
					<view class="props" v-if="getGoodSelectedProps(good)">
						{{ getGoodSelectedProps(good) }}
					</view>
				</view>
				<view class="btn-group">
					<button type="default" plain class="btn" size="mini" hover-class="none" @tap="handlePropertyReduce">
						<view class="iconfont icon-jianhao"></view>
					</button>
					<view class="number">{{ goodsDetail.number }}</view>
					<button type="primary" class="btn" size="min" hover-class="none" @tap="handlePropertyAdd">
						<view class="iconfont icon-plus"></view>
					</button>
				</view>
			</view>
			<view class="add-to-cart-btn" @tap="handleAddToCartInModal">
				<view>加入购物车</view>
			</view>
		</modal>
		<!-- 商品详情模态框 end -->
		<!-- 购物车详情popup -->
		<popuplayer direction="top" :show-pop="cartPopupVisible" class="cart-popup">
			<template slot="content">
				<view class="top">
					<text @tap="handleCartClear">清空</text>
				</view>
				<scroll-view class="cart-list" scroll-y>
					<view class="wrapper">
						<view class="item" v-for="(item, index) in cart" :key="index">
							<view class="left">
								<view class="name">{{ item.goodsName }}</view>
								<view class="props">{{ item.props_text }}</view>
							</view>
							<view class="center">
								<text>￥{{ item.price }}</text>
							</view>
							<view class="right">
								<button type="default" plain size="mini" class="btn" hover-class="none"
									@tap="handleCartItemReduce(index)">
									<view class="iconfont icon-jianhao"></view>
								</button>
								<view class="number">{{ item.number }}</view>
								<button type="primary" class="btn" size="min" hover-class="none"
									@tap="handleCartItemAdd(index)">
									<view class="iconfont icon-plus"></view>
								</button>
							</view>
						</view>
						<view class="item" v-if="orderType == 'takeout' ">
							<view class="left">
								<view class="name">包装费</view>
							</view>
							<view class="center">
								<text>￥{{ 5 }}</text>
							</view>
							<view class="right invisible">
								<button type="default" plain size="mini" class="btn" hover-class="none">
									<view class="iconfont icon-jianhao"></view>
								</button>
								<view class="number">1</view>
								<button type="primary" class="btn" size="min" hover-class="none">
									<view class="iconfont icon-plus"></view>
								</button>
							</view>
						</view>
					</view>
				</scroll-view>
			</template>
		</popuplayer>
		<!-- 购物车详情popup -->
	</view>
	<!-- 	<view class="loading" v-else>
		<image src="/static/images/loading.gif"></image>
	</view> -->
</template>

<script setup>
	import modal from '@/components/modal/modal'
	import popuplayer from '@/components/popup-layer/popup-layer'
	// import {mapState, mapMutations, mapActions, mapGetters} from 'vuex'
	// import goods from "/pages/common/goods.js"
	import {
		ref,
		computed,
		nextTick,
		reactive,
		getCurrentInstance
	} from "vue"
	import {
		onLoad,
		onShow,
		onUnload
	} from '@dcloudio/uni-app';

	//用户仓库
	import {
		userInfo
	} from '../../stores/userInfo'

	let UserInfo = userInfo()

	let shopDetailData = ref({})

	let ads = ref([{
			image: 'https://img-shop.qmimg.cn/s23107/2020/04/27/4ebdb582a5185358c4.jpg?imageView2/2/w/600/h/600'
		},
		{
			image: 'https://images.qmai.cn/s23107/2020/05/08/c25de6ef72d2890630.png?imageView2/2/w/600/h/600'
		},
		{
			image: 'https://img-shop.qmimg.cn/s23107/2020/04/10/add546c1b1561f880d.jpg?imageView2/2/w/600/h/600'
		},
		{
			image: 'https://images.qmai.cn/s23107/2020/04/30/b3af19e0de8ed42f61.jpg?imageView2/2/w/600/h/600'
		},
		{
			image: 'https://img-shop.qmimg.cn/s23107/2020/04/17/8aeb78516d63864420.jpg?imageView2/2/w/600/h/600'
		}
	])

	let orderType = ref('takein')

	let shopAddressData = reactive([])

	let isLogin = ref(false)

	let scrollProHei = ref(0)

	let loading = ref(true)
	let currentCateId = ref(0) //默认分类
	let cateScrollTop = ref(0)
	let menuScrollIntoView = ref('')
	let cart = ref([]) //购物车
	let goodDetailModalVisible = ref(false) //是否饮品详情模态框
	let good = reactive({}) //当前饮品
	let category = reactive({}) //当前饮品所在分类
	let cartPopupVisible = ref(false)
	let sizeCalcState = ref(false)

	let goodsDetail = reactive({})

	let shopAddId = ref(0)

	let userOrderAddress = ref({}) // 用户订单地址


	let goodCartNum = computed(() => { //计算单个饮品添加到购物车的数量
		return (id) => cart.value.reduce((acc, cur) => {
			if (cur.id === id) {
				return acc += cur.number
			}
			return acc
		}, 0)

		uni.setStorageSync('cart', {
			data: JSON.parse(JSON.stringify(cart.value)),
			ShopId: shopAddId.value
		})
	})

	let menuCartNum = computed(() => {
		return (id) => cart.value.reduce((acc, cur) => {
			if (cur.cate_id === id) {

				return acc += cur.number
			}

			return acc
			console.log(cur.cate_id === id, acc, "222")
		}, 0)
	})
	let getCartGoodsNumber = computed(() => { //计算购物车总数
		return cart.value.reduce((acc, cur) => acc + cur.number, 0)
	})
	let getCartGoodsPrice = computed(() => { //计算购物车总价
		return cart.value.reduce((acc, cur) => acc + cur.number * cur.price, 0).toFixed(2)
	})
	let disabledPay = computed(() => { //是否达到起送价
		// console.log(orderType.value == 'takeout' && (getCartGoodsPrice.value < 50) ? true : false,"是否达到起送价",getCartGoodsPrice.value)
		return orderType.value == 'takeout' && (getCartGoodsPrice.value < 50) ? true : false
	})
	let spread = computed(() => { //差多少元起送
		if (orderType.value != 'takeout') return
		return parseFloat((50 - getCartGoodsPrice.value).toFixed(2))
	})


	// 获取图片地址
	let getImgUrl = computed(() => {
		return UserInfo.getimgUrl()
	})

	let init = () => { //页面初始化


		let results = uni.getStorageSync('cart') || []
		// console.log("resultsfefesfse")
		// console.log(results.ShopId == shopAddId.value,results.ShopId , shopAddId.value,"真的没有调用吗")
		if (results.ShopId == shopAddId.value) {
			cart.value = results.data
		}
		uni.getSystemInfo({
			success: (res) => {
				const statusBarHeight = res.statusBarHeight;
				const navBarHeight = 44;
				// usableHeight.value = res.windowHeight - (statusBarHeight + navBarHeight);
				scrollProHei.value = res.windowHeight - 36 - 70;
				// console.log("可用高度:", usableHeight.value,scrollProHei.value);
			}
		});

	}



	let takein = (data) => {
		console.log(data, "data")
		orderType.value = data
	}

	let takout = (data) => {
		orderType.value = data
		console.log(orderType.value, "orderType.value")


		if (isLogin.value) {
			uni.navigateTo({
				url: '/pages/login/login'
			})
			return
		}

		let results = uni.getStorageSync('userOrderAddress') || {}

		// console.log(isEmptyObject(results), results,"用户地址result")
		if (isEmptyObject(results)) {
			// console.log(results, "用户地址resultsfefes")
			uni.navigateTo({
				url: '/pages/mine/addressList?is_choose=true'
			})
		} else {
			userOrderAddress.value = results
		}


		// uni.navigateTo({
		// 	url: '/pages/mine/addressList?is_choose=true'
		// })
	}

	let isEmptyObject = (obj) => {
		// 1. 类型校验
		if (typeof obj !== 'object' || obj === null) {
			return false
		}

		// 2. 原型链判断
		const isPlainObject = Object.getPrototypeOf(obj) === Object.prototype

		// 3. 属性检测
		return isPlainObject &&
			Reflect.ownKeys(obj).length === 0 && // 检测 Symbol 属性
			Object.getOwnPropertyNames(obj).length === 0
	}


	let handleMenuTap = (id) => { //点击菜单项事件
		if (!sizeCalcState.value) {
			calcSize()
		}

		currentCateId.value = id
		nextTick(() => cateScrollTop.value = shopAddressData.find(item => item.id == id).top)
		// console.log("滑动位置",cateScrollTop.value,'---',shopAddressData.find(item => item.id == id))
	}
	let handleGoodsScroll = ({
		detail
	}) => { //商品列表滚动事件
		if (!sizeCalcState.value) {
			calcSize()
		}
		const {
			scrollTop
		} = detail
		let tabs = shopAddressData.filter(item => item.top <= scrollTop).reverse()
		if (tabs.length > 0) {
			currentCateId.value = tabs[0].id
		}
	}
	let calcSize = () => {
		let h = 10

		let view = uni.createSelectorQuery().select('#ads')
		view.fields({
			size: true
		}, data => {
			h += Math.floor(data.height)
		}).exec()


		shopAddressData.forEach(item => {
			console.log(item, "shopAddressData")
			let view = uni.createSelectorQuery().select(`#cate-${item.id}`)
			view.fields({
				size: true
			}, data => {
				item.top = h
				h += data.height
				item.bottom = h
			}).exec()
		})
		sizeCalcState.value = true
	}
	let handleAddToCart = (cate, good, num) => { //添加到购物车
		const index = cart.value.findIndex(item => {
			if (good.use_property) {
				return (item.id === good.id) && (item.props_text === good.props_text)
			} else {
				return item.id === good.id
			}
		})
		if (index > -1) {
			// console.log("中")
			cart.value[index].number += num
			uni.setStorageSync('cart', {
				data: JSON.parse(JSON.stringify(cart.value)),
				ShopId: shopAddId.value
			})
		} else {
			// console.log("没中")
			cart.value.push({
				id: good.id,
				cate_id: cate.id,
				name: good.goodsName,
				price: good.price,
				number: good.num,
				image: good.goodsImg,
				use_property: good.use_property,
				props_text: good.introduction,
				props: good.props
			})
			uni.setStorageSync('cart', {
				data: JSON.parse(JSON.stringify(cart.value)),
				ShopId: shopAddId.value
			})
		}
	}
	let handleReduceFromCart = (item, good) => {
		// console.log(item, good)
		const index = cart.value.findIndex(item => item.id === good.id)
		cart.value[index].number -= 1
		if (cart.value[index].number <= 0) {
			cart.value.splice(index, 1)
		}

		uni.setStorageSync('cart', {
			data: JSON.parse(JSON.stringify(cart.value)),
			ShopId: shopAddId.value
		})
	}
	let showGoodDetailModal = (item, good) => {
		// good.value = {...good, number: 1}
		// category.value = item
		Object.assign(goodsDetail, JSON.parse(JSON.stringify({
			...good,
			number: 1
		})))
		// good = 
		Object.assign(category, JSON.parse(JSON.stringify(item)))
		// category= JSON.parse(JSON.stringify(item))
		goodDetailModalVisible.value = true


		// console.log(good,category,"这是你爹")
	}
	let closeGoodDetailModal = () => { //关闭饮品详情模态框
		goodDetailModalVisible.value = false
		category.value = {}
		good.value = {}
	}
	let changePropertyDefault = (index, key) => { //改变默认属性值
		this.good.property[index].values.forEach(value => this.$set(value, 'is_default', 0))
		this.good.property[index].values[key].is_default = 1
		this.good.number = 1
	}
	let getGoodSelectedProps = (good, type = 'text') => { //计算当前饮品所选属性
		if (good.use_property) {
			let props = []
			good.property.forEach(({
				values
			}) => {
				values.forEach(value => {
					if (value.is_default) {
						props.push(type === 'text' ? value.value : value.id)
					}
				})
			})
			return type === 'text' ? props.join('，') : props
		}
		return ''
	}
	let handlePropertyAdd = () => {
		this.good.number += 1
	}
	let handlePropertyReduce = () => {
		if (this.good.number === 1) return
		this.good.number -= 1
	}
	let handleAddToCartInModal = () => {

		// console.log(goodsDetail,"为什么会没有了呢")
		const product = Object.assign({}, goodsDetail, {
			props_text: getGoodSelectedProps(goodsDetail),
			props: getGoodSelectedProps(goodsDetail, 'id')
		})
		handleAddToCart(category, product, goodsDetail.number)
		closeGoodDetailModal()
	}
	let openCartPopup = () => { //打开/关闭购物车列表popup
		cartPopupVisible.value = !cartPopupVisible.value
	}
	let handleCartClear = () => { //清空购物车
		uni.showModal({
			title: '提示',
			content: '确定清空购物车么',
			success: ({
				confirm
			}) => {
				if (confirm) {
					cartPopupVisible.value = false
					cart.value = []
				}
			}
		})
	}
	let handleCartItemAdd = (index) => {
		cart.value[index].number += 1

		uni.setStorageSync('cart', {
			data: JSON.parse(JSON.stringify(cart.value)),
			ShopId: shopAddId.value
		})
	}
	let handleCartItemReduce = (index) => {
		if (cart.value[index].number === 1) {
			cart.value.splice(index, 1)
			uni.setStorageSync('cart', {
				data: JSON.parse(JSON.stringify(cart.value)),
				ShopId: shopAddId.value
			})
		} else {
			cart.value[index].number -= 1
			uni.setStorageSync('cart', {
				data: JSON.parse(JSON.stringify(cart.value)),
				ShopId: shopAddId.value
			})
		}
		if (!cart.value.length) {
			cartPopupVisible.value = false
		}
	}
	let toPay = () => {

		if (isLogin.value) {
			uni.navigateTo({
				url: '/pages/login/login'
			})
			return
		}

		shopDetailData.value['orderType'] = orderType.value
		uni.showLoading({
			title: '加载中'
		})
		// uni.setStorageSync('cart', JSON.parse(JSON.stringify(cart.value)))
		// console.log(shopDetailData.value,"shopDetailData.value")

		uni.navigateTo({
			url: '/pages/menu/pay',
			success: function(res) {
				// 通过eventChannel向被打开页面传送数据
				res.eventChannel.emit('emitShopAddress', {
					data: shopDetailData.value
				})
			}
		})
		// cart.value = []
		uni.hideLoading()
	}





	//获取店铺商品的数据
	let getStoreAddressData = async (e) => {


		let res = await UserInfo.getStoreShopData(e)

		currentCateId.value = res[0].id

		Object.assign(shopAddressData, res)

		// console.log(res,"这是店铺的商品")

	}


	//获取传过来的shopId
	onLoad((option) => {
		const instance = getCurrentInstance().proxy
		const eventChannel = instance.getOpenerEventChannel();
		eventChannel.on('accpetshopAddId', async (data) => {
			// console.log(data.data,"这是传过来的店铺id")
			shopAddId.value = data.data.id
			shopDetailData.value = data.data
			getStoreAddressData({
				shopAddId: data.data.id
			})

		})
		init()
	})


	// 页面显示的时候就显示一下
	onShow(() => {
		let results = uni.getStorageSync('userOrderAddress') || {}
		
		userOrderAddress.value = results
		init()
	})
</script>

<style lang="scss" scoped>
	@import '/pages/menu/menu.scss';
</style>